package com.lagou.zookeeper.api;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.io.IOException;

public class DeleteNote implements Watcher {

//    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    private static ZooKeeper zooKeeper;

    /**
     * 建立会话
     */
    public static void main(String[] args) throws IOException, InterruptedException, KeeperException {

        /*
         客户端可以通过创建⼀个zk实例来连接zk服务器
         new Zookeeper(connectString,sesssionTimeOut,Wather)
         connectString: 连接地址：IP：端⼝
         sesssionTimeOut：会话超时时间：单位毫秒
         Wather：监听器(当特定事件触发监听时，zk会通过watcher通知到客户端)
         */
        zooKeeper = new ZooKeeper("127.0.0.1:2180", 5000, new DeleteNote());
        System.out.println(zooKeeper.getState());
        //计数工具类， CountDownLacth： 不让main结束， 让线程处于等待阻塞状态
//        countDownLatch.await();
        Thread.sleep(Integer.MAX_VALUE);
//        System.out.println("客户端与服务端回话真正建立了");
    }

    public void process(WatchedEvent watchedEvent) {
        //当连接创建了，服务端发送给客户端SyncConnected事件
        if(watchedEvent.getState() == Event.KeeperState.SyncConnected){
            //解除主程序CountDownLatch上的等待阻塞
            System.out.println("process方法执行了......");
//            countDownLatch.countDown();
            //创建节点 同步
            try {
                deleteNoteSync();
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void deleteNoteSync() throws KeeperException, InterruptedException {

        /*
         zooKeeper.exists(path,watch) :判断节点是否存在
         zookeeper.delete(path,version) : 删除节点
         */
        Stat exists = zooKeeper.exists("/ghc-persistent/c1", false);
        System.out.println(exists == null ? "该节点不存在":"该节点存在");
        if (exists != null){
            zooKeeper.delete("/ghc-persistent/c1", -1);
        }
        Stat exists2 = zooKeeper.exists("/ghc-persistent/c1", false);
        System.out.println(exists2 == null ? "该节点不存在":"该节点存在");
    }
}
